package com.daily.daily_push.excel;

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class ExcelExport {
    public static void main(String[] args) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("专项费用计划-集团总部");

        // 合并单元格
        int[][] mergeRegions = {
                {0, 2, 0, 0}, {0, 2, 1, 1}, {0, 2, 2, 2}, {0, 2, 3, 3},
                {0, 0, 4, 8}, {1, 1, 4, 6}, {1, 1, 7, 8}
        };



        // 记录已添加的区域，防止重复和重叠
        Set<String> mergedCells = new HashSet<>();

        for (int[] region : mergeRegions) {
            String key = region[0] + "," + region[1] + "," + region[2] + "," + region[3];

            boolean hasOverlap = mergedCells.stream().anyMatch(existing -> {
                String[] parts = existing.split(",");
                int[] existingRegion = {Integer.parseInt(parts[0]), Integer.parseInt(parts[1]),
                        Integer.parseInt(parts[2]), Integer.parseInt(parts[3])};
                return isOverlapping(region, existingRegion);
            });

            if (!hasOverlap) {
                sheet.addMergedRegion(new CellRangeAddress(region[0], region[1], region[2], region[3]));
                mergedCells.add(key);
            }
        }

        // 创建标题行并填充随机数据
        Random random = new Random();
        for (int rowNum = 0; rowNum <= 10; rowNum++) {
            XSSFRow row = sheet.createRow(rowNum);
            for (int colNum = 0; colNum <= 27; colNum++) {
                XSSFCell cell = row.createCell(colNum);
                cell.setCellValue(random.nextInt(100)); // 生成0-99的随机数
            }
        }

        // 保存到D盘
        try (FileOutputStream fos = new FileOutputStream("D:/专项费用计划.xlsx")) {
            workbook.write(fos);
            System.out.println("Excel 文件已成功生成并保存到D盘！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 检查区域是否重叠的方法
    static boolean isOverlapping(int[] region1, int[] region2) {
        return !(region1[1] < region2[0] || region1[0] > region2[1] ||
                region1[3] < region2[2] || region1[2] > region2[3]);
    }
}
